<template>
  <div class="createPost-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-row>
          <el-col :span="24">
            <div class="postInfo-container">
              <fieldset class="fieldInfo">
                <legend>
                  <span>用户主要信息</span>
                </legend>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
                      label-width="115px"
                      label="用户名"
                      prop="userLoginAccount"
                      class="postInfo-container-item"
                    >
                      <el-input placeholder="请输入用户名" v-model="postForm.userLoginAccount"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item
                      label-width="115px"
                      label="真实姓名"
                      prop="userName"
                      class="postInfo-container-item"
                    >
                      <el-input placeholder="请输入真实姓名" v-model="postForm.userName"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item
                      label-width="100px"
                      label="密码"
                      prop="userLoginPassword"
                      class="postInfo-container-item"
                    >
                      <el-input
                        placeholder="请输入密码"
                        v-model="postForm.userLoginPassword"
                        show-password
                      ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item
                      label-width="115px"
                      label="联系电话"
                      prop="userTelNumber"
                      class="postInfo-container-item"
                    >
                      <el-input placeholder="请输入电话号码" v-model="postForm.userTelNumber"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </fieldset>

              <fieldset class="fieldInfo">
                <legend>
                  <span>用户其他信息</span>
                </legend>
                <el-row>
                  <el-col :span="24">
                    <el-form-item
                      label-width="115px"
                      label="所属组织"
                      prop="organization"
                      class="postInfo-container-item"
                    >
                      <el-select
                        v-model="postForm.organization.id"
                        placeholder="请选择组织机构"
                        style="width: 300px"
                        ref="organizationTree"
                      >
                        <el-option
                          :value="postForm.organization.id"
                          :label="postForm.organization.name"
                          style="height:200px;overflow: auto;background-color:#fff"
                        >
                          <el-tree
                            ref="organizationTree"
                            :data="organizationData"
                            node-key="id"
                            default-expand-all
                            :expand-on-click-node="false"
                            @node-click="handleOrganizationNodeClick"
                            :props="defaultProps"
                          ></el-tree>
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item
                      label-width="115px"
                      label="是否主管"
                      prop="orgChiefFlag"
                      class="postInfo-container-item"
                    >
                      <el-radio-group v-model="postForm.orgChiefFlag">
                        <el-radio :label="0">否</el-radio>
                        <el-radio :label="1">是</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item
                      label-width="115px"
                      label="选中角色"
                      prop="roles"
                      class="postInfo-container-item"
                    >
                      <el-checkbox-group v-model="postForm.roles">
                        <el-checkbox
                          :label="role.id"
                          :value="role.id"
                          v-for="(role) in this.rolesData"
                          :key="role.id"
                        >{{role.roleName}}</el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-col>
                </el-row>
              </fieldset>
              <el-row>
                <el-col :span="24">
                  <el-form-item style="text-align: center;">
                    <el-button
                      type="primary"
                      @click="submitForm"
                      :loading="loadingbut"
                    >{{loadingbuttext}}</el-button>
                    <el-button @click="closeCurrentTag">关闭</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
// import MDinput from '@/components/MDinput'
// import { validURL, validUsername } from '@/utils/validate'
import { getRoles } from '@/api/role'
import { fetchTreeData } from '@/api/organization'
import {
  addUser,
  editUser,
  fetchUserDataById,
  fetchList,
  doubleUserAccount
} from '@/api/user'
import qs from 'qs'
const defaultForm = {
  status: 'draft',
  // title: '', // 文章题目
  // content: '', // 文章内容
  // content_short: '', // 文章摘要
  // source_uri: '', // 文章外链
  // image_uri: '', // 文章图片
  // display_time: undefined, // 前台展示时间
  id: undefined
  // platforms: ['a-platform'],
  // comment_disabled: false,
  // importance: 0
}

export default {
  name: 'UserDetail',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    var validateEngUserName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能为空'))
      } else {
        const reg = /^[a-zA-Z0-9]+$/
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('用户名只能是英文名称'))
        }
      }
    }
    var validateUserLoginAccount = (rule, value, callback) => {
      if (!this.isEdit) {
        if (!value) {
          return callback(new Error('用户名不能为空'))
        } else {
          let data = {
            userLoginAccount: value
          }
          doubleUserAccount(data)
            .then((res) => {
              // if (res.code != 20000) {
              //   return callback(new Error('该用户名已被占用'))
              // } else {
              //   callback()
              // }
              if (res.code == 20000) {
                callback()
              } else {
                return callback(new Error('该用户名已被占用'))
              }
            })
            .catch((err) => {
              return callback(new Error('该用户名已被占用'))
            })
        }
      } else {
        callback()
      }
    }
    var validatePhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      } else {
        const reg = /^1[3|4|5|7|8][0-9]\d{8}$/
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback()
        } else {
          return callback(new Error('请输入正确的手机号'))
        }
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能为空'))
      } else {
        const reg = /^[a-zA-Z0-9]+$/
        // console.log(reg.test(value));
        if (reg.test(value)) {
          if (value.length < 6) {
            return callback(new Error('密码长度不够'))
          } else {
            callback()
          }
        } else {
          return callback(new Error('密码只能是英文或数字'))
        }
      }
    }
    const addUser = {
      userLoginAccount: '',
      userName: '',
      roles: [],
      userLoginPassword: '',
      userTelNumber: '',
      organization: {
        id: '',
        name: ''
      },
      orgChiefFlag: 0
    }
    return {
      loadingbut: false, //新增用户按钮
      loadingbuttext: '保存',
      userId: '',
      postForm: Object.assign({}, addUser),
      loading: false,
      // userListOptions: [],
      rules: {
        userLoginAccount: [
          { required: true, message: '用户名不能为空', trigger: 'blur' },
          { validator: validateEngUserName, trigger: 'blur' },
          { validator: validateUserLoginAccount, trigger: 'blur' }
        ],
        userName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        userLoginPassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        roles: [{ required: true, message: '角色不能为空', trigger: 'blur' }],
        organization: [
          { required: true, message: '组织不能为空', trigger: 'blur' }
        ],
        orgChiefFlag: [
          { required: true, message: '是否主管不能为空', trigger: 'blur' }
        ],
        userTelNumber: [
          { required: true, message: '电话号码不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      tempRoute: {},
      organizationData: [], //组织树
      rolesData: [], //角色列表
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getTreeData()
    this.getRolesList()
    if (this.isEdit) {
      //如果是编辑数据
      this.userId = this.$route.params && this.$route.params.id
      console.log('userId', this.userId)

      this.fetchUserData(this.userId)
    }
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    closeCurrentTag() {
      // 调用全局挂载的方法
      this.$store.dispatch('tagsView/delView', this.$route)
      // 返回上一步路由
      this.$router.go(-1)
    },
    getTreeData() {
      fetchTreeData({
        rootId: 0
      }).then((response) => {
        // console.log(response.data)
        this.organizationData = response.data
      })
    },
    getRolesList() {
      getRoles(1).then((response) => {
        console.log('roles---------------', response.data)

        this.rolesData = response.data.filter((role) => {
          return role.roleStatus == 1
        })
      })
    },
    //根据id获取用户数据信息
    fetchUserData(id) {
      fetchUserDataById(id)
        .then((response) => {
          let result = response.data
          this.postForm.userLoginAccount = result.userLoginAccount
          this.postForm.userName = result.userName
          this.postForm.userLoginPassword = result.userLoginPassword
          this.postForm.userTelNumber = result.userTelNumber
          this.postForm.organization = {
            id: result.orgId,
            name: result.strOrgName
          }
          this.postForm.orgChiefFlag = Number(result.orgChiefFlag)
          this.postForm.roles = result.roles.map((role) => {
            if (role.roleStatus == 1) {
              return role.id
            }
          })
          // set tagsview title
          this.setTagsViewTitle()
          // set page title
          this.setPageTitle()
        })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = '编辑用户'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.userLoginAccount}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = '编辑用户'
      document.title = `${title} - ${this.postForm.userName}`
    },
    submitForm() {
      this.loadingbut = true
      this.loadingbuttext = '保存中...'
      //保存新增用户
      console.log('postFomr', this.postForm)
      this.$refs.postForm.validate((valid) => {
        console.log('valid', valid)
        console.log('this.postForm.roles', this.postForm.roles)
        if (valid) {
          let params = {
            userName: this.postForm.userName,
            userLoginAccount: this.postForm.userLoginAccount,
            roles: this.postForm.roles,
            userLoginPassword: this.postForm.userLoginPassword,
            userTelNumber: this.postForm.userTelNumber,
            orgId: this.postForm.organization.id,
            orgChiefFlag: this.postForm.orgChiefFlag
          }
          this.loading = true
          if (!this.isEdit) {
            //如果是新增用户
            addUser(params).then((res) => {
              if (res.success) {
                this.$notify({
                  title: '成功',
                  message: '新增用户成功',
                  type: 'success',
                  duration: 2000
                })
                this.postForm.status = 'published'
                this.loading = false
                this.loadingbut = false
                this.loadingbuttext = '保存'
              } else {
                this.$notify({
                  title: '失败',
                  message: '新增用户失败',
                  type: 'error',
                  duration: 2000
                })
                this.loadingbut = false
                this.loadingbuttext = '保存'
              }
            })
          } else {
            //如果是编辑用户
            params.id = this.userId
            editUser(params).then((res) => {
              if (res.success) {
                this.$notify({
                  title: '成功',
                  message: '编辑用户成功',
                  type: 'success',
                  duration: 2000
                })
                this.postForm.status = 'published'
                this.loading = false
                this.loadingbut = false
                this.loadingbuttext = '保存'
              } else {
                this.$notify({
                  title: '失败',
                  message: '编辑用户失败',
                  type: 'error',
                  duration: 2000
                })
                this.loadingbut = false
                this.loadingbuttext = '保存'
              }
            })
          }
        } else {
          // console.log('error submit!!')
          this.$notify({
            title: '失败',
            message: '用户验证失败',
            type: 'error',
            duration: 2000
          })
          this.loadingbut = false
          this.loadingbuttext = '保存'
          return false
        }
      })
    },
    // draftForm() {
    //   if (
    //     this.postForm.content.length === 0 ||
    //     this.postForm.title.length === 0
    //   ) {
    //     this.$message({
    //       message: '请填写必要的标题和内容',
    //       type: 'warning'
    //     })
    //     return
    //   }
    //   this.$message({
    //     message: '保存成功',
    //     type: 'success',
    //     showClose: true,
    //     duration: 1000
    //   })
    //   this.postForm.status = 'draft'
    // },
    // getRemoteUserList(query) {
    //   searchUser(query).then((response) => {
    //     if (!response.data.items) return
    //     this.userListOptions = response.data.items.map((v) => v.name)
    //   })
    // },
    handleOrganizationNodeClick(node) {
      // console.log(node, 'node')
      this.postForm.organization.name = node.name
      this.postForm.organization.id = node.id
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/styles/mixin.scss';

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 5px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.fieldInfo {
  border-color: #eee;
  border-width: 1px;
  border-style: solid;
  margin-bottom: 20px;
  legend {
    color: #666;
  }
}
</style>
